package synchronicity.agent;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import synchronicity.host.SchedulerHost;
import synchronicity.util.Range;
import synchronicity.util.RangeSet;

/**
 * An agent that collects schedule data for a period of time from each host
 * it visits.
 */
public class ScheduleCollectorAgent extends Agent {
	
	public static final String TYPE = "ScheduleCollectorAgent";

	private Range timeRange;

	private RangeSet busyTimes;

	public ScheduleCollectorAgent(Range timeRange, RangeSet initialBusyTimes) {
		this.timeRange = timeRange;
		this.busyTimes = initialBusyTimes;
	}

	/**
	 * For streaming this class only.
	 */
	public ScheduleCollectorAgent() {

	}

	/**
	 * Combine all the times the host is occupied with the
	 * times already marked in the RangeSet
	 */
	protected void visitHost(SchedulerHost host) {
		RangeSet hostBusyTimes = host.getBusyTimes(timeRange);
		this.busyTimes = busyTimes.union(hostBusyTimes);
	}

	public RangeSet getBusyTimes() {
		return busyTimes;
	}

	protected void readAgent(DataInputStream stream) throws IOException {
		timeRange = new Range(0, 0);
		timeRange.read(stream);
		busyTimes = new RangeSet();
		busyTimes.read(stream);
	}

	protected void writeAgent(DataOutputStream stream) throws IOException {
		timeRange.write(stream);
		busyTimes.write(stream);
	}
	
	public String getType() {
		return TYPE;
	}
}
